<template>
    <div class="area-edit" style="height: 90%;">
        <div class="area-header">
            <h2>{{ state.newOrEdit == 'edit' ? '编辑电子围栏' : '新增电子围栏' }}</h2>
        </div>
        <div class="area-content" style="flex: 1; overflow-y: auto;overflow-x: hidden;">
            <a-row :gutter="48">
                <a-col :span="10">
                    <!-- 基础信息表单 -->
                    <div class="form-section">
                        <a-row :gutter="24">
                            <a-col :span="24">
                                <a-form-item label="电子围栏名称" required  :label-col="{ style: 'width:120px' }">
                                    <a-input v-model:value="formState.name" placeholder="请输入名称"
                                        style="width: 100%" />
                                </a-form-item>
                            </a-col>
                            <a-col :span="24">
                                <a-form-item label="区域类型"  :label-col="{ style: 'width:120px' }">
                                    <a-select v-model:value="formState.type" placeholder="请选择"
                                        style="width: 100%" allowClear>
                                        <a-select-option v-for="item in getEnumOptions('fenceType')" :key="item.value" :value="item.value">{{ item.label }}</a-select-option>
                                    </a-select>
                                </a-form-item>
                            </a-col>
                        </a-row>
                        <a-row :gutter="24">
                            <a-col :span="24">
                                <a-form-item label="关联车企"  :label-col="{ style: 'width:120px' }">
                                    <a-select v-model:value="formState.manufacturerId" placeholder="请选择关联车企"
                                        style="width: 100%" allowClear>
                                        <a-select-option v-for="item in state.manufacturerList" :key="item.id" :value="item.id">{{ item.name }}</a-select-option>
                                        <!-- <a-select-option value="1">上海仙途智能科技有限公司</a-select-option> -->
                                    </a-select>
                                </a-form-item>
                            </a-col>
                        </a-row>
                    </div>

                    <!-- 绘制区域 -->
                    <div class="draw-section">
                        <h3>绘制区域</h3>


                        <!-- 区域列表 -->
                        <div class="area-list">
                            <a-table :columns="areaColumns" :data-source="formState.areaList" :pagination="false"
                                size="small">
                                <template #bodyCell="{ column, record, index }">
                                    <!-- <template v-if="column.dataIndex === 'area'">
                                        <a-input v-model:value="record.name" placeholder="区域名称"
                                            @change="updatename(index)" />
                                    </template> -->
                                     <!-- <template v-if="column.dataIndex === 'lo'">
                                       <a-tooltip :title="`经度: ${record.lo}`">
                                            <a-input v-model:value="record.lo" placeholder="经度"
                                                @change="updateCoordinates(index)" />
                                        </a-tooltip>
                                        
                                    </template>
                                    <template v-if="column.dataIndex === 'la'">
                                       <a-tooltip :title="`纬度: ${record.la}`">
                                            <a-input v-model:value="record.la" placeholder="纬度"
                                                @change="updateCoordinates(index)" />
                                        </a-tooltip>
                                    </template> -->
                                    <template v-if="column.dataIndex === 'name'">
                                        <a-input v-model:value="record.name" placeholder="区域名称" />
                                    </template>
                                    <template v-if="column.dataIndex === 'la' || column.dataIndex === 'lo'">
                                        <a-dropdown>
                                            <div>
                                                {{column.dataIndex === 'la'? record.path[0].la : record.path[0].lo}}
                                            </div>
                                            <template #overlay>
                                                <a-menu>
                                                    <a-menu-item>多边形区域</a-menu-item>
                                                    <a-menu-item
                                                        v-if="record.path && record.path.length > 0">
                                                        <div style="padding: 8px;">
                                                            <div v-for="(coord, idx) in record.path" :key="idx">
                                                                {{ idx + 1 }}:[{{ coord.lo }},{{ coord.la }}]
                                                            </div>
                                                        </div>
                                                    </a-menu-item>
                                                </a-menu>
                                            </template>
                                        </a-dropdown>
                                    </template>
                                    <template v-if="column.dataIndex === 'operation'">
                                        
                                        <a @click="editArea(index)" style="margin-left: 8px; color: #1890ff;">编辑</a>
                                        <a @click="deleteArea(index)" style="margin-left: 8px; color: #ff4d4f;">删除</a>
                                    </template>
                                </template>
                            </a-table>
                            <div class="area-note">
                                注:当绘制了多个围栏时,那么当前电子围栏为所有绘制区域的合集。
                            </div>
                        </div>
                    </div>
                    <a-form-item label="备注">
                        <a-textarea v-model:value="formState.description" placeholder="请输入备注信息" :maxlength="50" :rows="3"
                            show-count />
                    </a-form-item>
                </a-col>
                <a-col :span="14">
                    <!-- 地图区域 -->
                    <div class="map-container">
                        <div class="map-header">
                            <a-input placeholder="搜索/选择地址" id='search_station' style="width: 200px;"/>
                            <div class="map-controls">
                                <a-button :type="state.isDrawing ? 'primary' : 'default'" @click="toggleDrawing"
                                    size="small">
                                    <EditOutlined />
                                </a-button>
                                <a-button :type="state.isSatellite ? 'primary' : 'default'" @click="toggleSatellite"
                                    size="small">
                                    <GlobalOutlined />
                                </a-button>
                            </div>
                        </div>
                        <div id="area-map" class="map-content"></div>
                    </div>
                </a-col>
            </a-row>
        </div>
        <!-- 备注和操作按钮 -->
        <div class="bottom-section">


            <div class="action-buttons">
                <a-button @click="handleCancel">取消</a-button>
                <a-button type="primary" class="ant-btn" @click="handleConfirm">确认</a-button>
            </div>
        </div>
    </div>
</template>

<script setup>
import { reactive, ref, onMounted, onUnmounted } from 'vue'
import { EditOutlined, GlobalOutlined } from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import { bizFenceAdd,bizFenceDetail,bizFenceUpdate } from '@/service/nmcApi'
import { getEnumOptions } from '@/utils/enum'
import { getManufacturerCompany } from '@/utils/baseData'

const emit = defineEmits(['update:visible', 'success'])

const state = reactive({
    newOrEdit: 'add', // add 新增 edit 编辑
    isDrawing: false,
    isSatellite: false,
    manufacturerList: []
})

const formState = reactive({
    name: '',
    type: null,  // 区域类型
    manufacturerId: null,  // 默认关联车企
    areaList: [],
    description: '',
    id:null
})



// 区域表格列配置
const areaColumns = [
    {
        title: '区域',
        dataIndex: 'name',
        width: 100
    },
    {
        title: '经度',
        dataIndex: 'lo',
        width: 120
    },
    {
        title: '纬度',
        dataIndex: 'la',
        width: 120
    },
    {
        title: '操作',
        dataIndex: 'operation',
        width: 120
    }
]

// 地图相关变量
let mapInstance = null
let polygons = [] // 存储多个多边形
let mouseTool = null
let satellite = null
let polyEditor = null
let currentEditingPolygon = null
let gaoAutoComplete = null

onMounted(() => {
    initMap()

})

onUnmounted(() => {
    if (mapInstance) {
        mapInstance.destroy()
    }
})

// 初始化地图
const initMap = () => {
    mapInstance = new AMap.Map('area-map', {
        mapStyle: 'amap://styles/whitesmoke',
        doubleClickZoom: false,
        zoom: 13,
        center: [114.325512, 30.367111],
        animateEnable: false
    })

    // 初始化卫星图层
    satellite = new AMap.TileLayer.Satellite()
    mapInstance.addLayer(satellite)
    satellite.hide()
    mapInstance.plugin(['AMap.AutoComplete'], () => {
        gaoAutoComplete = new AMap.AutoComplete({
            input: 'search_station',
        })
        gaoAutoComplete.on('select', handleSelectResult)
    })
    // 初始化多边形编辑器
    polyEditor = new AMap.PolygonEditor(mapInstance)
    polyEditor.on('addnode', updateAreaData)
    polyEditor.on('removenode', updateAreaData)
    polyEditor.on('adjust', updateAreaData)

    // 初始化鼠标工具
    mouseTool = new AMap.MouseTool(mapInstance)
    mapInstance.add(mouseTool)

    // 绘制完成事件
    mouseTool.on('draw', (event) => {
        mouseTool.close(true)
        state.isDrawing = false

        const path = event.obj._opts.path
        if (path.length > 2) {
            addNewArea(path)
        }
    })

    // 地图点击事件
    mapInstance.on('click', (e) => {
        if (state.isDrawing) {
            // 绘制模式下的点击处理
        }
    })
}
//高德搜索
const handleSelectResult = (e) => {
    // console.log(e.poi, searchMarker)
    if (e.poi.location) {
        const { lng, lat } = e.poi.location;
        // 地图重新定位
        mapInstance.setCenter(e.poi.location);
        mapInstance.setZoom(16);
    }
}
// 加载编辑数据
const loadEditData = async(data,type) => {

    
    // type   new 新增  edit 编辑
    state.newOrEdit = type 

    if(type == 'edit'){
        bizFenceDetail({id:data.id}).then(res => {
            let $data = res.result
            formState.name = $data.name
            formState.type = $data.type
            formState.manufacturerId = $data.manufacturerId;
            formState.description = $data.description
            formState.id = $data.id
            formState.areaList =$data.bizFenceAreaList ? $data.bizFenceAreaList.map(item => {
                return {
                    name: item.name,
                    path: item.pointList
                }
            }) : []

            drawAreas()
        })
        
        
    }else{
        formState.name = ''
        formState.type = null,  // 区域类型
        formState.manufacturerId = null,  // 默认关联车企
        formState.areaList = []
        formState.description = ''
        formState.id = null;
        drawAreas()
    }

    state.isDrawing = false
    state.isSatellite = false
    // 获取运营企业
    state.manufacturerList = await getManufacturerCompany()
}

// 添加新区域
const addNewArea = (path) => {
    const name = `区域${formState.areaList.length + 1}`
    // const center = calculateCenter(path)
    // const firstPoint = path[0]
    formState.areaList.push({
        name,
        // path: path,
        // coordinates: path.map(point => [point[1], point[0]]) // 存储坐标点用于显示
        path: path.map(point => {
            return {
                lo: point[0],
                la: point[1]
            }
        }) // 存储坐标点用于显示
    
    })
    console.log(formState.areaList, 'formState.areaList')
    
    drawAreas()
}

// 计算区域中心点
// const calculateCenter = (path) => {
//     let lngSum = 0
//     let latSum = 0

//     path.forEach(point => {
//         lngSum += point[0]
//         latSum += point[1]
//     })

//     return {
//         lng: lngSum / path.length,
//         lat: latSum / path.length
//     }
// }

// 绘制所有区域
const drawAreas = () => {
    // 清除现有多边形
    polygons.forEach(polygon => {
        mapInstance.remove(polygon)
    })
    polygons = []

    if (formState.areaList.length > 0) {
        formState.areaList.forEach((area, index) => {
            if (area.path && area.path.length > 0) {
                const polygon = new AMap.Polygon({
                    path: area.path.map(point => [point.lo, point.la]),
                    fillColor: '#006EFF',
                    fillOpacity: 0.2,
                    strokeWeight: 2,
                    strokeColor: '#006EFF',
                    extData: { index } // 存储索引用于识别
                })

                mapInstance.add(polygon)
                polygons.push(polygon)

                // 绑定点击事件
                polygon.on('click', () => {
                    if (polyEditor) {
                        currentEditingPolygon = polygon
                        polyEditor.setTarget(polygon)
                        polyEditor.open()
                    }
                })
            }
        })

        // 调整视图以显示所有多边形
        if (polygons.length > 0) {
            mapInstance.setFitView(polygons, false, [60, 60, 60, 60], 16)
        }
    }
}

// 更新区域数据
const updateAreaData = (e) => {
    const path = e.target._opts.path
    if (path.length > 0 && currentEditingPolygon) {
        const index = currentEditingPolygon.getExtData().index
        if (index !== undefined && formState.areaList[index]) {
            // const center = calculateCenter(path)
        
            // formState.areaList[index].path = path
            // formState.areaList[index].coordinates = path.map(point => [point[1], point[0]])
            formState.areaList[index].path = path.map(point => {
                return {
                    lo: point[0],
                    la: point[1]
                }
            })
        }
    }
}

// 更新区域名称
const updatename = (index) => {
    // 区域名称更新逻辑
}

// 更新坐标
// const updateCoordinates = (index) => {
//     const area = formState.areaList[index]
//     if (area.lo && area.la) {
//         // 更新路径并重新绘制
//         area.path = [[parseFloat(area.lo), parseFloat(area.la)]]
//         area.coordinates = area.path.map(point => [point[1], point[0]])
//         drawAreas()
//     }
// }

// 编辑区域
const editArea = (index) => {
    if (polygons[index]) {
        currentEditingPolygon = polygons[index]
        polyEditor.setTarget(polygons[index])
        polyEditor.open()
    }
}

// 删除区域
const deleteArea = (index) => {
    formState.areaList.splice(index, 1)
    drawAreas()
}

// 切换绘制模式
const toggleDrawing = () => {
    state.isDrawing = !state.isDrawing
    if (state.isDrawing) {
        polyEditor.close()
        mouseTool.polygon({
            fillColor: '#006EFF',
            fillOpacity: 0.2,
            strokeWeight: 2,
            strokeColor: '#006EFF'
        })
    } else {
        mouseTool.close(true)
    }
}

// 切换卫星图层
const toggleSatellite = () => {
    state.isSatellite = !state.isSatellite
    if (state.isSatellite) {
        satellite.show()
    } else {
        satellite.hide()
    }
}

// 搜索位置
// const searchLocation = () => {
//     if (searchAddress.value) {
//         // 实现地址搜索功能
//         console.log('搜索地址:', searchAddress.value)
//     }
// }

// 取消
const handleCancel = () => {
    emit('update:visible', false)
}

// 确认
const handleConfirm = () => {
    if (!formState.name) {
        message.error('请输入电子围栏名称')
        return
    }

    if (formState.areaList.length === 0) {
        message.error('请至少绘制一个区域')
        return
    }

    const submitData = {
        ...formState,
        // id:formState.id
    }
    submitData.manufacturerName = state.manufacturerList.find(item => item.id === formState.manufacturerId)?.name
    let axiosFn = state.newOrEdit == 'edit' ? bizFenceUpdate : bizFenceAdd
    axiosFn(submitData).then(res => {
        console.log(res, 'res')
    })
    // 这里可以调用API保存数据
    console.log('提交数据:', submitData)

    message.success(state.newOrEdit == 'edit' ? '编辑成功' : '新增成功')
    emit('success', submitData)
    emit('update:visible', false)
}

// 暴露方法给父组件
defineExpose({
    loadEditData
})
</script>

<style scoped lang="less">
.area-edit {
    height: 100%;
    background: #fff;
    // border-radius: 3px;
    // padding: 24px; 
    overflow: hidden;
    position: relative;
    display: flex;
    flex-direction: column;

    // padding-bottom: 80px;
    // overflow-y: auto;
    .area-header {
        margin-bottom: 24px;

        h2 {
            margin: 0;
            font-size: 18px;
            font-weight: 500;
        }
    }

    .form-section {
        margin-bottom: 24px;
        padding: 16px;
        background: #fafafa;
        border-radius: 6px;
    }

    .draw-section {
        flex: 1;
        margin-bottom: 24px;

        h3 {
            margin-bottom: 16px;
            font-size: 16px;
            font-weight: 500;
        }

        .area-list {
            height: 100%;

            .area-note {
                margin-top: 8px;
                font-size: 12px;
                color: #999;
                line-height: 1.4;
            }
        }


    }

    .map-container {
        height: 100%;
        border: 1px solid #d9d9d9;
        border-radius: 6px;
        overflow: hidden;

        .map-header {
            padding: 12px;
            background: #fafafa;
            border-bottom: 1px solid #d9d9d9;
            display: flex;
            justify-content: space-between;
            align-items: center;

            .map-controls {
                display: flex;
                gap: 8px;
            }
        }

        .map-content {
            height: calc(100% - 60px);
            min-height: 400px;
        }
    }

    .bottom-section {

        padding-top: 16px;
        border-top: 1px solid #f0f0f0;

        // position: absolute;
        // bottom: 0;
        // left: 0;
        // right: 0;
        // padding: 16px;
        // background: #fff;
        .action-buttons {
            text-align: right;
            margin-top: 16px;

            .ant-btn {
                margin-left: 8px;
            }
        }
    }
}
</style>